package com.platform.common.util;

import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.util.function.Consumer;

/**
 * describe: 编程式事务工具
 * 作用是接收一个Service层需要被事务包围的方法为参数，然后给调用端返回事务结果，供调用端根据结果做相应的处理
 * @author rainly
 * @date 2020/5/3
 * @time 8:53 下午
 */
@Component
public class TransactionUtil {
    @Resource
    private PlatformTransactionManager transactionManager;

    /**
     * 接受service类方法
     * @param consumer Service
     * @return boolean
     */
    public boolean transact(Consumer consumer) {
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        try {
            consumer.accept(null);
            transactionManager.commit(status);
            return true;
        } catch (Exception e) {
            transactionManager.rollback(status);
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 开启事务
     * @return TransactionStatus
     */
    public TransactionStatus open() {
        return transactionManager.getTransaction(new DefaultTransactionDefinition());
    }

    /**
     * 提交事务
     * @param ts TransactionStatus
     */
    public void commit(TransactionStatus ts) {
        transactionManager.commit(ts);
    }

    /**
     * 回滚事务
     * @param ts TransactionStatus
     */
    public void rollback(TransactionStatus ts) {
        transactionManager.rollback(ts);
    }
}
